package Fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;

import org.json.JSONArray;
import org.json.JSONException;

import service.StudentService;
import www.truongnha.com.R;
import Config.setting;
import TruongNhaLib.DatabaseHandler;
import TruongNhaLib.EListAdapterMarkForStd;
import TruongNhaLib.JSONParser;
import TruongNhaLib.SubjectMark;
import TruongNhaLib.Term;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.Spinner;
import android.widget.Toast;

public class StudentSchoolFragment extends Fragment implements
		OnItemSelectedListener {
	private Timer timer = new Timer();
	private int delay = 0;
	private int period = setting.getRefreshTime();
	private Intent doneLoading;
	private static String host = setting.getHost();
	private static String url_student_mark_cur_term = host
			+ "api/markForAStudent/"; // + student_id
	private static String url_student_get_term = host + "api/getListTerm";
	private Button f5;
	private Spinner term_spinner;
	private int cur_spinner_row_id = -1;// mean doesn't load term id yet.
	private HashMap<String, String> userDetail;
	private List<String> array_term_string = new ArrayList<String>();
	// expandable
	private ExpandableListView eList;
	private EListAdapterMarkForStd eListAdapter;
	ArrayList<SubjectMark> arraySubMarkOld = new ArrayList<SubjectMark>();
	int cur_term_id = -1;
	int old_term_id = -1;
	boolean compare = false;
	ArrayList<SubjectMark> arraySubMark = new ArrayList<SubjectMark>();
	ArrayList<Term> arrayTerm = new ArrayList<Term>();
	ArrayAdapter<String> adapter;
	// variable for service
	private IntentFilter intentFilter;
	private BroadcastReceiver intentReceiver;
	private StudentService ssv;
	private boolean connected = false;
	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder binder) {
			Log.d("main", "onServiceConnected");
			ssv = ((StudentService.MyBinder) binder).getService();
			if (ssv != null) {
				if (ssv.dataLoaded())
					new getMarkFromService().execute("");
			}
			Toast.makeText(getActivity().getApplicationContext(), "Connected",
					Toast.LENGTH_SHORT).show();
			connected = true;
		}

		public void onServiceDisconnected(ComponentName className) {
			Toast.makeText(getActivity().getApplicationContext(),
					"Disconnected", Toast.LENGTH_SHORT).show();
			// Log.d("main", "onServiceDisConnected");
			connected = false;
			ssv = null;
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.student_school, container, false);
		startIntervalService();
		eList = (ExpandableListView) view.findViewById(R.id.expandlist);
		eListAdapter = new EListAdapterMarkForStd(getActivity()
				.getApplicationContext(), arraySubMark);
		eList.setAdapter(eListAdapter);
		// Custom intentReceiver
		intentReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				if (ssv == null) {
					Toast.makeText(getActivity().getApplicationContext(),
							"ssv == null", Toast.LENGTH_SHORT).show();
					return;
				}
				doneLoading = new Intent();
				doneLoading.setAction("DONE_LOADING_ACTION");
				doneLoading.putExtra("doneLoading", true);
				getActivity().getApplicationContext()
						.sendBroadcast(doneLoading);
				new getMarkFromService().execute("");
				/*
				 * arraySubMark = ssv.getArraySubmark();
				 * Toast.makeText(getActivity(),
				 * "receive: "+arraySubMark.get(0).
				 * getChilds(0)+arraySubMark.get(
				 * 0).getChilds(1)+arraySubMark.get(0).getChilds(2),
				 * Toast.LENGTH_SHORT).show();
				 * 
				 * eListAdapter= new
				 * EListAdapterMarkForStd(getActivity().getApplicationContext
				 * (),arraySubMark); eList.setAdapter(eListAdapter);
				 * 
				 * eList.setOnGroupClickListener(new OnGroupClickListener() {
				 * public boolean onGroupClick(ExpandableListView parent, View
				 * v, int groupPosition, long id) { // TODO Auto-generated
				 * method stub if(arraySubMark.get(groupPosition).getStatus() !=
				 * 0){ arraySubMark.get(groupPosition).setStatus(0);
				 * eListAdapter.notifyDataSetChanged(); } return false; } });
				 */}
		};
		intentFilter = new IntentFilter();
		intentFilter.addAction("DONE_REFRESH_MARK");
		f5 = (Button) view.findViewById(R.id.f5);
		f5.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// send start command to service
				Intent doneLoading = new Intent();
				doneLoading.setAction("DONE_LOADING_ACTION");
				doneLoading.putExtra("doneLoading", false);
				getActivity().getApplicationContext()
						.sendBroadcast(doneLoading);
				Intent service = new Intent(getActivity()
						.getApplicationContext(), StudentService.class);
				getActivity().startService(service);
			}

		});

		/*
		 * //Create db object: DatabaseHandler db = new
		 * DatabaseHandler(getActivity().getApplicationContext()); // Get data
		 * for main Class userDetail = db.getUserDetails(); term_spinner
		 * =(Spinner)view.findViewById(R.id.term_spinner);
		 * term_spinner.setOnItemSelectedListener(this);
		 * 
		 * f5 =(Button)view.findViewById(R.id.f5); f5.setOnClickListener(new
		 * View.OnClickListener() { public void onClick(View v) { // TODO
		 * Auto-generated method stub Log.d("f5", "click f5");
		 * if(cur_spinner_row_id == -1){//mean doesn't load alltermid-> user
		 * current term with blank_id new
		 * getMarkTask().execute(url_student_mark_cur_term +
		 * userDetail.get("user_id")); }else{//alltermid loaded, get current
		 * term to load compare = true; new
		 * getMarkTask().execute(url_student_mark_cur_term +
		 * userDetail.get("user_id")+"/"+
		 * arrayTerm.get(cur_spinner_row_id).getTerm_id()); } }
		 * 
		 * });
		 *//*
			 * timer.scheduleAtFixedRate(new TimerTask() {
			 * 
			 * @Override public void run() { // TODO Auto-generated method stub
			 * Log.d("f5", "auto f5 after " + period +"s" ); //compare = true;
			 * sau lan dau tien new
			 * getMarkTask().execute(url_student_mark_cur_term +
			 * userDetail.get("user_id")); }
			 * 
			 * }, delay, period );
			 */
		// new getAllTermTask().execute(url_student_get_term);

		return view;
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
		// Load mark for update
		// if(ssv!= null){
		// if(ssv.dataLoaded())
		// new getMarkFromService().execute("");
		// }
		// Register the receiver---
		Log.d("registerReceiver", "registerReceiver");
		getActivity().registerReceiver(intentReceiver, intentFilter);
	}

	@Override
	public void onDestroy() {
		Log.d("unbind in onPause", "unbind");
		if (connected) {
			getActivity().getApplicationContext().unbindService(mConnection);
			connected = false;
		}
		// unregister receiver
		Log.d("unregister", "unregister");
		getActivity().unregisterReceiver(intentReceiver);
		timer.cancel();
		super.onDestroy();
	}

	public void onItemSelected(AdapterView<?> parent, View view, int pos,
			long id) {
		// An item was selected. You can retrieve the selected item using
		// parent.getItemAtPosition(pos)
		if (cur_spinner_row_id != (int) id) {
			cur_spinner_row_id = (int) id;
			Term term = arrayTerm.get(cur_spinner_row_id);
			Log.d("spinner",
					parent.getItemAtPosition(pos) + " "
							+ parent.getItemIdAtPosition(pos) + " "
							+ term.getTerm_id() + term.getNumber()
							+ term.getYear());
			compare = false;// Vi the nay la chon ky khac nen se khong so sanh
			new getMarkTask().execute(url_student_mark_cur_term
					+ userDetail.get("user_id") + "/" + term.getTerm_id());
		}
	}

	public void onNothingSelected(AdapterView<?> parent) {
		// Another interface callback
		Log.d("spinner", "Nothing selected");
	}

	private void compareMark(ArrayList<SubjectMark> oldM,
			ArrayList<SubjectMark> newM) {
		if (oldM.size() != newM.size())
			return;
		int size = oldM.size();
		for (int i = 0; i < size; i++) {
			if (oldM.get(i).getId() != newM.get(i).getId())
				continue;
			newM.get(i).copyStatus(oldM.get(i));// copy current unread status
			newM.get(i).compare(oldM.get(i));
		}

	}

	class getMarkFromService extends AsyncTask<String, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", false);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
		}

		@Override
		protected Void doInBackground(String... params) {
			arraySubMark = ssv.getArraySubmark();
			eListAdapter = new EListAdapterMarkForStd(getActivity()
					.getApplicationContext(), arraySubMark);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Broadcast to main activity when done loading
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", true);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					eList.setAdapter(eListAdapter);
					eList.setOnGroupClickListener(new OnGroupClickListener() {
						public boolean onGroupClick(ExpandableListView parent,
								View v, int groupPosition, long id) {
							if (arraySubMark.get(groupPosition).getStatus() != 0) {
								arraySubMark.get(groupPosition).setStatus(0);
								eListAdapter.notifyDataSetChanged();
							}
							return false;
						}
					});
				}
			});
			if (arraySubMark.size() > 0)
				Toast.makeText(
						getActivity(),
						"receive: " + arraySubMark.get(0).getChilds(0)
								+ arraySubMark.get(0).getChilds(1)
								+ arraySubMark.get(0).getChilds(2),
						Toast.LENGTH_SHORT).show();
		}
	}// End class

	class getMarkTask extends AsyncTask<String, Void, Void> {
		String message;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			message = "";
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", false);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
		}

		@Override
		protected Void doInBackground(String... params) {
			JSONArray mark_array = new JSONParser().getJSONArray(params[0]);
			int size = mark_array.length();
			if (size == 1) {// May be error, check error
				try {
					message = mark_array.getString(0);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (!message.equals(""))// no error.
				return null;
			arraySubMarkOld.clear();
			arraySubMarkOld = new ArrayList<SubjectMark>(arraySubMark);
			arraySubMark.clear();
			try {
				// add new
				for (int i = 0; i < size; i++) {
					// Log.d("test", "i = " + i);
					SubjectMark sm = new SubjectMark(
							mark_array.getJSONObject(i));
					arraySubMark.add(sm);
				}
				// Log.d("size = ", arraySubMark.size() +" " );
			} catch (JSONException e) {
				e.printStackTrace();
			}
			if (compare) {
				// Compare here
				compareMark(arraySubMarkOld, arraySubMark);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Broadcast to main activity when done loading
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", true);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
			if (message.equals("")) {// no error
				eListAdapter.notifyDataSetChanged();
				eList.setOnGroupClickListener(new OnGroupClickListener() {
					public boolean onGroupClick(ExpandableListView parent,
							View v, int groupPosition, long id) {
						if (arraySubMark.get(groupPosition).getStatus() != 0) {
							arraySubMark.get(groupPosition).setStatus(0);
							eListAdapter.notifyDataSetChanged();
						}
						return false;
					}
				});
			}
		}
	}// End class getTimeTask

	class getAllTermTask extends AsyncTask<String, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", false);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
		}

		@Override
		protected Void doInBackground(String... params) {
			JSONArray term_array = new JSONParser().getJSONArray(params[0]);
			int size = term_array.length();
			try {
				for (int i = 0; i < size; i++) {
					Term term = new Term(term_array.getJSONObject(i));
					arrayTerm.add(term);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			if (size > 0) {
				array_term_string.clear();
				for (int i = 0; i < size; i++) {
					String term = "Kỳ " + arrayTerm.get(i).getNumber()
							+ ", Năm " + arrayTerm.get(i).getYear();
					array_term_string.add(term);
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Broadcast to main activity when done loading
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", true);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
			ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(
					getActivity().getApplicationContext(),
					R.layout.term_simple_spinner_item, array_term_string);
			spinnerAdapter
					.setDropDownViewResource(R.layout.term_simple_spinner_dropdown_item);
			term_spinner.setAdapter(spinnerAdapter);
			// set current term
			cur_spinner_row_id = array_term_string.size() - 1;
			term_spinner.setSelection(cur_spinner_row_id);

		}
	}// End class getTermTask

	private void startIntervalService() {
		Log.d("sendStart", "1");
		if (!isServiceRunning()) {// Not start yet, -> start
			Intent intent = new Intent();
			intent.setAction("START_SERVICE");
			intent.putExtra("start", true);
			getActivity().getApplicationContext().sendBroadcast(intent);
		}
		// bind
		getActivity().getApplicationContext().bindService(
				new Intent(getActivity(), StudentService.class), mConnection,
				Context.BIND_AUTO_CREATE);
	}

	private boolean isServiceRunning() {
		ActivityManager manager = (ActivityManager) getActivity()
				.getApplicationContext().getSystemService(
						Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if ("service.StudentService".equals(service.service.getClassName())) {
				Toast.makeText(getActivity().getApplicationContext(),
						"check: sv is running", Toast.LENGTH_SHORT).show();
				return true;
			}
		}
		return false;
	}

	/**
	 * Press back button twice to exit
	 */
	private long lastPressedTime;
	private Toast toast;

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			switch (event.getAction()) {
			case KeyEvent.ACTION_DOWN:
				if (event.getDownTime() - lastPressedTime < setting.PERIOD_TWICE_TO_EXIT) {
					toast.cancel();
					getActivity().finish();
				} else {
					toast = Toast.makeText(getActivity()
							.getApplicationContext(), "", Toast.LENGTH_SHORT);
					toast.setText("Nhấn back một lần nữa để thoát | student school gfragmet");
					toast.show();
					lastPressedTime = event.getEventTime();
				}
				return true;
			}
		}
		return false;
	}
}// end class
